package com.bugull.farm.core.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.concurrent.Callable;

import org.apache.logging.log4j.*;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.bugull.farm.core.store.Device;
import com.bugull.mongo.BuguDao;
import com.bugull.mongo.cache.DaoCache;

/**
 * 
 * @author songw
 *
 */
public class GetIPInfoCallable implements Callable<Boolean>{
	
	private String mac;
	private String ip;
	private Boolean success;//the task execute flag
	private final Logger logger = LogManager.getLogger(GetIPInfoCallable.class);
	
	public GetIPInfoCallable(String mac, String ip){
		this.mac = mac;
		this.ip = ip;
	}

	@Override
	public Boolean call() throws Exception {
		//illegal IP or Mac
		if(ip==null || ip.equals("") || mac==null || mac.equals("")){
			throw new Exception("Can't invoke the TaoBao interface with mac : " + mac +" , IP : " + ip);
		}
		String urlStr = "http://ip.taobao.com/service/getIpInfo.php?ip="+ip;
			try {
				String result = doHttpRequest(urlStr);
		        JSONObject node = JSONObject.parseObject(result);
		        int code = (Integer)node.get("code");
		      //query failed
		        if(code==1){
		        	this.success = Boolean.FALSE;
		        	return Boolean.FALSE;
		        }
		        JSONObject childNode = (JSONObject)node.get("data");
		        String country = (String)URLDecoder.decode(childNode.getString("country"), "UTF-8");
		        String region = (String)URLDecoder.decode(childNode.getString("region"), "UTF-8");
		        String city = (String)URLDecoder.decode(childNode.getString("city"), "UTF-8");
		        if(country.equals("") || region.equals("") || city.equals("")){
		        	urlStr = "http://api.ipinfodb.com/v3/ip-city/?key=47b538e0786e70c06ba6153fc18d2526361e58f4a9edf0c94939b2d3c1da18b2&format=json&ip=";
		        	result = doHttpRequest(urlStr);
			        node = JSONObject.parseObject(result);
			        String statusCode = (String)node.get("statusCode");
			      //query failed
			        if(!statusCode.equals("OK")){
			        	this.success = Boolean.FALSE;
			        	return Boolean.FALSE;
			        }
			        country = (String)URLDecoder.decode(childNode.getString("countryName"), "UTF-8");
			        region = (String)URLDecoder.decode(childNode.getString("regionName"), "UTF-8");
			        city = (String)URLDecoder.decode(childNode.getString("cityName"), "UTF-8");
		        }
		        BuguDao<Device> dao = DaoCache.getInstance().get(Device.class);
	            Device device = dao.findOne("macAddress", mac);
	        	device.setCountry(country);
	        	device.setRegion(region);
	        	device.setCity(city);
	        	dao.save(device);
	        	this.success = Boolean.TRUE;
		        return Boolean.TRUE;
			} catch (Exception e) {
				e.printStackTrace();
				this.success = Boolean.FALSE;
				return Boolean.FALSE;
			}
	}
	
	public Boolean isSuccess() {
		return success;
	}

	public String getMac() {
		return mac;
	}

	public String getIp() {
		return ip;
	}
	
	public String doHttpRequest(String urlStr){
		String result = "";
		try{
			URL url = new URL(urlStr);
			HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
			urlConn.setConnectTimeout(3000);
			urlConn.setReadTimeout(5000);
	        urlConn.connect();
	        InputStream is = urlConn.getInputStream();
	        BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
	        StringBuffer bs = new StringBuffer();
	        String l = null;
	        while((l=buffer.readLine())!=null){
	            bs.append(l);
	        }
	        result  = bs.toString();
	        result.replace("\"", "\'");
	        is.close();
		}catch(Exception e){
			e.printStackTrace();
			logger.error("request from the Url failed : "+urlStr);
			logger.error(e);
		}
        return result;
	}
}
